package com.qxzn.module.mine.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.AuthInfoBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EmergencyContactBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.mine.R;
import com.qxzn.module.mine.R2;
import com.qxzn.module.mine.adapter.ContactListAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.we.swipe.helper.WeSwipe;
import cn.we.swipe.helper.WeSwipeHelper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EmergencyContactActivity extends BaseActivity implements ContactListAdapter.DeletedItemListener, ContactListAdapter.EditItemListener {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.add_contact)
    View add_contact;

    ContactListAdapter contactListAdapter;

    @Override
    protected int initLayout() {
        return R.layout.activity_emergency_contact;
    }

    @Override
    protected void initView() {
        contactListAdapter = new ContactListAdapter(this);
        contactListAdapter.setDelectedItemListener(this);
        contactListAdapter.setEditItemListener(this);
        recyclerView.setAdapter(contactListAdapter);
    }

    @OnClick({R2.id.add_contact})
    public void onViewClicked(View view) {
        if (CommonUtil.isFastClick()) return;
        startActivityForResult(new Intent(this, AddEmergencyContactActivity.class), 1);
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText(R.string.emergency_contact_title);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        updateContact();
    }

    private boolean admin = false;

    private void getAuthInfo() {
        String deviceId = SharePreferenceUtil.getDeviceId(this);
        String userName = SharePreferenceUtil.getUserName(this);
        JSONObject param = new JSONObject();
        param.put("device_id", deviceId);
        HttpRequest.getService().getAuthInfo(HttpRequest.getDefaultBody(param)).enqueue(new Callback<BaseBean<AuthInfoBean>>() {
            @Override
            public void onResponse(Call<BaseBean<AuthInfoBean>> call, Response<BaseBean<AuthInfoBean>> response) {
                hideProgress();
                BaseBean<AuthInfoBean> body = response.body();
                if (body.getCode() == 200) {
                    AuthInfoBean data = body.getData();
                    if ("1".equals(data.user_role)) {
                        if (TextUtils.equals(userName, data.admin_id)) {
                            admin = true;
                            //设置WeSwipe。左滑显示编辑删除
                            WeSwipe.attach(recyclerView).setType(WeSwipeHelper.SWIPE_ITEM_TYPE_FLOWING);
                            showAdminView();
                        }
                    }
//                } else {
//                    ToastUtil.showTextToast(EmergencyContactActivity.this, body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean<AuthInfoBean>> call, Throwable t) {
                error();
            }
        });
    }

    private void showAdminView() {
        if (admin)
            add_contact.setVisibility(contactListAdapter.getData().size() < 3 ? View.VISIBLE : View.GONE);
    }

    private void updateContact() {
        showProgress();
        JSONObject params = new JSONObject();
        params.put("device_id", SharePreferenceUtil.getDeviceId(this));
        HttpRequest.getService().getEmergencyContact(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean<List<EmergencyContactBean>>>() {
            @Override
            public void onResponse(Call<BaseBean<List<EmergencyContactBean>>> call, Response<BaseBean<List<EmergencyContactBean>>> response) {
                BaseBean<List<EmergencyContactBean>> bean = response.body();
                if (bean.getCode() == 200) {
                    List<EmergencyContactBean> data = bean.getData();
                    if (data != null && data.size() > 0) {
                        contactListAdapter.setList(data);
                        showAdminView();
                    }
                } else {
                    ToastUtil.showTextToast(EmergencyContactActivity.this, bean.getMsg());
                }
                if (admin) {
                    hideProgress();
                } else {
                    getAuthInfo();
                }
            }

            @Override
            public void onFailure(Call<BaseBean<List<EmergencyContactBean>>> call, Throwable t) {
                error();
            }
        });
    }

    private void error() {
        hideProgress();
        ToastUtil.showTextToast(EmergencyContactActivity.this, getString(R.string.network_error));
    }

    @Override
    public void deleted(int position) {
        showProgress();
        EmergencyContactBean emergencyContactBean = contactListAdapter.getData().get(position);
        JSONObject params = new JSONObject();
        params.put("id", emergencyContactBean.emergency_id);
        HttpRequest.getService().deleteEmergencyContact(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                hideProgress();
                BaseBean bean = response.body();
                if (bean.getCode() == 200) {
                    ToastUtil.showTextToast(getApplicationContext(), emergencyContactBean.name + "已被删除");
                    contactListAdapter.removeDataByPosition(position);
                    add_contact.setVisibility(View.VISIBLE);
                } else {
                    ToastUtil.showTextToast(EmergencyContactActivity.this, bean.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                error();
            }
        });
    }

    @Override
    public void edit(int position) {
        Bundle bundle = new Bundle();
        EmergencyContactBean emergencyContactBean = contactListAdapter.getData().get(position);
        bundle.putSerializable("EmergencyContactBean", emergencyContactBean);
        startActivityForResult(new Intent(this, AddEmergencyContactActivity.class).putExtra("bean", bundle), 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            updateContact();
        }
    }
}
